const clientIn = (function () {
  var net = require('net')
  var mqttCon = require('mqtt-connection')
  var server = new net.Server()
  var res = {}

  server.on('connection', function (stream) {
    client = mqttCon(stream)
    res.publish = function(data, cb) {
      client.publish(data, cb)
    }

    client.on('connect', function (packet) {
      // acknowledge the connect packet
      client.connack({ returnCode: 0 });
    })

    // client published
    client.on('publish', function (packet) {
      let data = packet.payload.toString();
      console.log('send to out: ', data);
      serverNet.sendData(data)
    })

    // connection error handling
    client.on('close', function () { client.destroy() })
    client.on('error', function () { client.destroy() })
    client.on('disconnect', function () { client.destroy() })
    // stream timeout
    stream.on('timeout', function () { client.destroy(); })
  })
  // listen on port 1883
  server.listen(1883)

  return res
})()



const serverNet = (function () {
  const mqtt = require('mqtt')
  const host = '47.106.100.199'
  const port = '1883'
  const clientId = `mqtt_${Math.random().toString(16).slice(3)}`

  // connect options
  const OPTIONS = {
    clientId,
    clean: true,
    connectTimeout: 4000,
    username: 'test',
    password: 'test',
    reconnectPeriod: 1000,
  }
  let connectUrl = `mqtt://${host}:${port}`
  const topic = 'mqtt'
  const serverSocket = mqtt.connect(connectUrl, OPTIONS)
  //监听服务器开启
  serverSocket.on('connect', () => {
    console.log('服务器已连接')
    serverSocket.subscribe([topic + '/test_server'], () => {
      console.log(`已订阅'${topic}'`)
    })
  })

  serverSocket.on('error', (err) => {
    console.log('error: ', err)
  })

  //监听客户端发送的数据
  serverSocket.on('message', (topic, payload) => {
    clientIn.publish({ topic: topic + '/test_server', payload: payload }, function () {
      console.log('send to In: ', payload);
    })
  })

  serverSocket.sendData = function (data) {
    data = data || ''
    serverSocket.publish(topic + '/test_client', data, { qos: 2, retain: false }, (error) => {
      if (error) {
        console.error(error)
      }
    })
  }

  return serverSocket
})()
